package ru.usu.gv.view;

import ru.usu.gv.core.GraphCanvas;
import ru.usu.gv.uicomponents.UIEdge;
import ru.usu.gv.uicomponents.UIGraph;
import ru.usu.gv.uicomponents.UIVertex;

import javax.swing.event.MouseInputAdapter;
import javax.vecmath.Point2d;

import java.awt.event.MouseEvent;

/**
 @author Sergey Pupyrev 
 10.01.2007
 */

public class DragVertexPickingClient extends PickingClientBase<UIVertex>
{
	public void callback(MouseEvent e, final UIVertex vertex)
	{
		final MouseInputAdapter ma = new MouseInputAdapter()
		{
			private int prevX = -1;
			private int prevY = -1;

			@Override
			public void mouseDragged(MouseEvent e)
			{
				double distance = new Point2d(prevX, prevY).distance(new Point2d(e.getX(), e.getY()));
				double MIN_STEP = 20.0;
				if (prevX == -1 || distance > MIN_STEP)
				{
					reposition(e);
				}
			}

			@Override
			public void mouseReleased(MouseEvent e)
			{
				reposition(e);
				GraphCanvas.getInstance().removeMouseListener(this);
				GraphCanvas.getInstance().removeMouseMotionListener(this);
			}

			@Override
			public void mouseClicked(MouseEvent mevent)
			{
				//reposition(mevent);
			}

			private void reposition(MouseEvent e)
			{
				if (!e.isMetaDown() && !e.isAltDown())
				{
					UIGraph uiGraph = GraphCanvas.getInstance().getCurrentGraph();

					vertex.moveToCanvasPosition(e.getX(), e.getY());
					vertex.draw();
					for (UIEdge edge : uiGraph.getEdges(vertex))
						edge.draw();

					prevX = e.getX();
					prevY = e.getY();
				}
			}
		};

		GraphCanvas.getInstance().addMouseListener(ma);
		GraphCanvas.getInstance().addMouseMotionListener(ma);
	}
}
